﻿using System;
using System.Threading.Tasks;
using Jinjia.Approve.IService.JJFlow;
using Jinjia.Approve.IService.JJFlow.Action;
using JinJia.Core.Base.Exceptions;

namespace Jinjia.Approve.Service.JJFlow.Action
{
    public class JJFLowActionRecall : JJFlowActionGoTo, IJJFLowActionRecall
    {
        private readonly IJJFlowTemplateService _jjFlowTemplateService;

        public JJFLowActionRecall(IJJFlowInstanceService jjFlowInstanceService,
            IJJFlowTrackService jjFlowTrackService,
            IJJFlowTemplateService jjFlowTemplateService) : base(jjFlowInstanceService,
            jjFlowTrackService)
        {
            _jjFlowTemplateService = jjFlowTemplateService;
        }

        public async Task ReCall(int instance_id, int user_id)
        {
            var instance = await CheckAndGetFlowInstanceById(instance_id);
            if (instance.CreateUserId != user_id)
            {
                throw new BusinessException("暂无撤回权限！");
            }

            if (instance.Status != "0")
            {
                throw new BusinessException("此状态无法撤销申请！");
            }

            var template_info = await _jjFlowTemplateService.GetTemplateById(instance.TemplateId);

            if (template_info != null && template_info.IsRevoke == 0)
            {
                //判断是否被审批过
                var anyPassResult = await _jjFlowTrackService.GetApproveTrackModelByInstanceId(instance_id);
                if (anyPassResult)
                {
                    throw new BusinessException("该数据已审核，无法撤回！");
                }
            }

            instance.Status = "30"; //设置为 撤回
            instance.UpdateUserId = user_id;
            instance.UpdateTime = DateTime.Now;
            await _jjFlowInstanceService.Save(instance);
        }
    }
}